package models;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

import models.ticket.TicketMessage;

import org.mindrot.jbcrypt.BCrypt;

import play.db.ebean.Model;

import com.avaje.ebean.Page;

/*
 * User model
 * Author: Mamirey Uldana
 */

@Entity
public class User extends Model {
	@Id
	public Long id;

	@Column(unique = true)
	public String username;

	public String password;

	public String name, surname;

	@Column(unique = true)
	public String email;

	public String city;
	public String address;

	@OneToMany(mappedBy = "user", cascade = { CascadeType.ALL })
	List<TicketMessage> messages;

	@OneToMany(mappedBy = "user", cascade = { CascadeType.PERSIST,
			CascadeType.MERGE })
	List<UserOrder> orders;

	@Column(unique = true)
	@OneToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE,
			CascadeType.REMOVE })
	public Cart cart;

	@Column(nullable = false)
	public Integer role; // { 0 => User, 1 => Admin}

	public static Finder<Long, User> find = new Finder<Long, User>(Long.class,
			User.class);

	public static User create(String username, String password, String email) {
		User user = new User();
		user.username = username;
		user.password = BCrypt.hashpw(password.trim(), BCrypt.gensalt());
		user.email = email;
		user.role = 0;
		user.cart = Cart.create(user);
		return user;
	}

	public static User authenticate(String username, String password) {
		User user = find.where().eq("username", username).findUnique();
		if (user != null && BCrypt.checkpw(password.trim(), user.password)) {
			return user;
		} else {
			return null;
		}
	}

	public static Page<User> page(int page, int pageSize, String sortBy, String order, String filter)
	{
		Page<User> p;
		p = find.where()
				.ilike("username", "%"+filter+"%")
				.orderBy(sortBy + " " + order)
				.findPagingList(pageSize)
				.getPage(page);
		if(p.getTotalRowCount() == 0)
			p = find.where()
			.ilike("name", "%"+filter+"%")
			.orderBy(sortBy + " " + order)
			.findPagingList(pageSize)
			.getPage(page);
		if(p.getTotalRowCount() == 0)
			p = find.where()
			.ilike("surname", "%"+filter+"%")
			.orderBy(sortBy + " " + order)
			.findPagingList(pageSize)
			.getPage(page);
		return p;
	}
}